import axios from "axios"
import store from "@/store"
import { logOutAction } from "@/store/actions/login"
import { message } from "antd"
import customHistory from "./history"
const request = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0'
})
// 请求拦截器
request.interceptors.request.use((config) => {
  //获取token
  const { token } = store.getState()
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})
// 响应拦截器
request.interceptors.response.use((res) => {
  // 直接返回data给页面(action)
  return res.data
}, (error) => {
  console.dir(error)
  if (error.response.status === 401) {
    /**
     * 1.清除redux中存储的状态数据
     * 2.跳回登录页，携带当前页面的地址(目的：下次登陆，可以跳回上次登录的页面)
     */
    message.error(error.response.data.message)
    store.dispatch(logOutAction())
    // 通过history模块
    customHistory.replace({
      pathname: '/login',
      state: {
        from: customHistory.location.pathname
      }
    })
  }
  return Promise.reject(error)
})
export default request